package listener;


import entity.Users;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.*;
import java.util.HashSet;
import java.util.Set;

public class LoginUsersCountListener implements  HttpSessionAttributeListener, HttpSessionListener, ServletContextListener {
        ServletContext application;

    @Override
    public void contextInitialized(ServletContextEvent sc) {
        Set<Users> userList=new HashSet<>();
        application = sc.getServletContext();
        application.setAttribute("userList",userList);

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent he) {
        HttpSession session=he.getSession();
        Users user= (Users) session.getAttribute("user");
        Set<Users> userList= (Set<Users>) application.getAttribute("userList");
        userList.add(user);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent he) {
        Users user= (Users) he.getValue();
        Set<Users> userList= (Set<Users>) application.getAttribute("userList");
        userList.remove(user);
        System.out.println("鸡肋");
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {


    }

    @Override
    public void sessionDestroyed(HttpSessionEvent hse) {
        HttpSession session=hse.getSession();
        Users user= (Users) session.getAttribute("user");
        Set<Users> userList= (Set<Users>) application.getAttribute("userList");
        userList.remove(user);
        System.out.println("鸡胸脯");
    }
}
